package com.general;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.ResultSet;
import java.util.concurrent.*;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-09 14:36:06
 */
public class TimeoutPeriodController {

    private static final Logger log = LoggerFactory.getLogger(TimeoutPeriodController.class);

    public static <T> T executeFuture(ExecutorService executor, long timeout, TimeUnit unit, Callable<T> task) throws Exception {
        // 提交任务并获取Future
        Future<T> future = executor.submit(task);
        try {
            // 在指定时间内获取结果
            return future.get(timeout, unit);
        } catch (TimeoutException e) {
            // 超时，取消任务
            future.cancel(true); // true表示中断正在执行的任务
            log.error("任务执行超时被中断");
            throw e;
        } catch (Exception ae) {
            log.error("任务执行异常被中断");
            throw ae;
        }
    }


    public static ResultSet executeSQL(ExecutorService executor, long timeout, TimeUnit unit, SQLTask task) throws Exception {

        Future<ResultSet> future = executor.submit(task);

        try {
            return future.get(timeout, unit);
        } catch (TimeoutException e) {
            log.error("任务超时，正在取消SQL执行...");
            task.cancelSQL();
            future.cancel(true);
            throw e;
        }
    }

}
